package cn.source.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.source.common.annotation.Log;
import cn.source.common.config.RuoYiConfig;
import cn.source.common.constant.UserConstants;
import cn.source.common.core.controller.BaseController;
import cn.source.common.core.domain.AjaxResult;
import cn.source.common.core.domain.entity.SysRole;
import cn.source.common.core.domain.entity.SysUser;
import cn.source.common.core.page.TableDataInfo;
import cn.source.common.enums.BusinessType;
import cn.source.common.utils.StringUtils;
import cn.source.common.utils.file.FileUploadUtils;
import cn.source.system.domain.DeyuArticle;
import cn.source.system.domain.DeyuDevice;
import cn.source.system.domain.DeyuDialysis;
import cn.source.system.domain.DeyuDialysisList;
import cn.source.system.service.*;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 小程序数据Controller
 *
 * @author deyucare.com
 * @date 2025-02-18
 */
@Api("小程序数据")
@RestController
@RequestMapping("/deyu/miniWxApi")
public class DeyuMiniWXController extends BaseController {

    @Autowired
    private IDeyuDialysisService deyuDialysisService;

    @Autowired
    private IDeyuSysUserService deyuSysUserService;

    @Value("${ruoyi.domain}")
    private String domain;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IDeyuDeviceService deyuDeviceService;

    @Autowired
    private IDeyuLogFileService deyuLogFileService;

    @Autowired
    private IDeyuArticleService deyuArticleService;

    /**
     * 用户信息获取
     */
    @ApiOperation("用户信息获取")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        AjaxResult ajax = AjaxResult.success();
        Long userId = getUserId();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }


    /**
     * 用户信息修改
     */
    @ApiOperation("用户信息修改")
    @Log(title = "用户信息修改", businessType = BusinessType.UPDATE)
    @PutMapping("/editUserInfo")
    public AjaxResult editUserInfo(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        user.setUserId(getUserId());
        // 不让修改用户名和用户类型
        user.setUserName(null);
        user.setUserType(null);
        return toAjax(deyuSysUserService.updateSysUser(user));
    }


    /**
     * 查询腹透记录列表
     */
    @ApiOperation("查询腹透记录列表")
    @GetMapping("/list")
    public TableDataInfo list(DeyuDialysis deyuDialysis) {
        startPage();
        deyuDialysis.setUserId(getUserId());
        List<DeyuDialysis> list = deyuDialysisService.selectDeyuDialysisList(deyuDialysis);
        return getDataTable(list);
    }

    /**
     * 获取腹透记录详细信息
     */
    @ApiOperation("获取腹透记录详细信息")
    @ApiImplicitParam(name = "id", value = "腹透记录ID", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    @GetMapping(value = "/detail/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DeyuDialysis dialysis = new DeyuDialysis();
        dialysis.setId(id);
        dialysis.setUserId(getUserId());
        return AjaxResult.success(deyuDialysisService.selectDeyuDialysisById(dialysis));
    }

    /**
     * 获取腹透最近一条记录详细信息
     */
    @ApiOperation("获取腹透最近一条记录详细信息")
    @ApiImplicitParam(name = "deviceMac", value = "设备的 MAC 地址", required = false, dataType = "String", paramType = "query", dataTypeClass = String.class)
    @GetMapping(value = "/getRecent")
    public AjaxResult getRecentInfo(@RequestParam(value = "deviceMac", required = false) String deviceMac) {
        DeyuDialysis dialysis = new DeyuDialysis();
        dialysis.setUserId(getUserId());
        dialysis.setDeviceMac(deviceMac);
        PageHelper.startPage(1, 1, "completed_time desc").setReasonable(true);
        List<DeyuDialysis> dialyses = deyuDialysisService.selectDeyuDialysisList(dialysis);
        DeyuDialysis dialysisResponse = null;
        if (CollectionUtil.isNotEmpty(dialyses)) {
            dialysisResponse = dialyses.get(0);
        }
        return AjaxResult.success(dialysisResponse);
    }

    /**
     * 按天统计腹透数据概要
     */
    @ApiOperation("按天统计腹透数据概要")
    @GetMapping(value = "/summaryByDay")
    public TableDataInfo summaryByDay() {
        startPage();
        DeyuDialysis dialysis = new DeyuDialysis();
        dialysis.setUserId(getUserId());
        List<DeyuDialysis> dialyses = deyuDialysisService.summaryByDay(dialysis);
        return getDataTable(dialyses);
    }

    /**
     * 新增腹透记录
     */
    @ApiOperation("新增腹透记录")
    @Log(title = "腹透记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody DeyuDialysis deyuDialysis) {
        int rows = 0;
        if (Objects.nonNull(deyuDialysis)) {
            deyuDialysis.setUserId(getUserId());
            // 执行插入操作
            rows = deyuDialysisService.insertDeyuDialysis(deyuDialysis);
        }
        return toAjax(rows);
    }

    /**
     * 批量新增腹透记录
     */
    @ApiOperation("批量新增腹透记录")
    @Log(title = "批量新增腹透记录", businessType = BusinessType.INSERT)
    @PostMapping("/addBatch")
    public AjaxResult addBatch(@Validated @RequestBody DeyuDialysisList deyuDialysisList) {
        int rows = 0;
        if (Objects.nonNull(deyuDialysisList) && CollectionUtil.isNotEmpty(deyuDialysisList.getDeyuDialysis())) {
            deyuDialysisList.getDeyuDialysis().forEach(d -> d.setUserId(getUserId()));
            // 执行批量插入操作
            rows = deyuDialysisService.insertBatchDeyuDialysis(deyuDialysisList.getDeyuDialysis());
        }
        return toAjax(rows);
    }

    /**
     * 透析液照片上传
     */
    @ApiOperation("透析液照片上传")
    @PostMapping("/upload/{deviceMac}/{completedTime}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "透析液照片", required = true, dataType = "file", paramType = "form", dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "deviceMac", value = "设备mac地址", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class),
            @ApiImplicitParam(name = "completedTime", value = "导出时间时间戳", required = true, dataType = "Long", paramType = "path", dataTypeClass = Long.class)
    })
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @PathVariable("deviceMac") String deviceMac, @PathVariable("completedTime") Long completedTime) throws Exception {
        try {
            // 处理时间戳的逻辑
            Date completedDate = new Date(completedTime); // 将时间戳转换为 Date 类型
            // 真实文件名
            String realName = file.getOriginalFilename();
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = domain + fileName;
            // 更新透析记录
            DeyuDialysis dialysis = new DeyuDialysis();
            dialysis.setCompletedTime(completedDate);
            dialysis.setDialysisImg(fileName);
            dialysis.setUserId(getUserId());
            dialysis.setDeviceMac(deviceMac);
            int i = deyuDialysisService.updateForCompletedTime(dialysis);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("realName", realName);
            ajax.put("url", url);
            //更新最近那条数据
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 根据设备mac地址查询用户设备信息
     */
    @ApiOperation("根据设备mac地址查询用户设备信息")
    @ApiImplicitParam(name = "deviceMac", value = "设备mac地址", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
    @GetMapping(value = "/getDevice/{deviceMac}")
    public AjaxResult getDevice(@PathVariable("deviceMac") String deviceMac) {
        DeyuDevice device = new DeyuDevice();
        device.setUserId(getUserId());
        device.setDeviceMac(deviceMac);
        PageHelper.startPage(1, 1, "update_time desc").setReasonable(true);
        List<DeyuDevice> list = deyuDeviceService.selectDeyuDeviceList(device);
        DeyuDevice deviceResponse = null;
        if (CollectionUtil.isNotEmpty(list)) {
            deviceResponse = list.get(0);
        }
        return AjaxResult.success(deviceResponse);
    }

    /**
     * 绑定设备
     */
    @ApiOperation("绑定设备")
    @Log(title = "绑定设备", businessType = BusinessType.INSERT)
    @PostMapping("/addDevice")
    public AjaxResult addDevice(@Validated @RequestBody DeyuDevice deyuDevice) {
        deyuDevice.setUserId(getUserId());
        List<DeyuDevice> list = deyuDeviceService.selectDeyuDeviceList(deyuDevice);
        if (CollectionUtil.isNotEmpty(list)){
            return error("请勿重复绑定");
        }
        return toAjax(deyuDeviceService.insertDeyuDevice(deyuDevice));
    }

    /**
     * 解绑设备
     */
    @ApiOperation("解绑设备")
    @ApiImplicitParam(name = "ids", value = "设备id数组", required = true, dataType = "array", paramType = "path", dataTypeClass = Long[].class)
    @Log(title = "解绑设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deyuDeviceService.updateDeyuDeviceUserIdToNull(ids,getUserId()));
    }

    /**
     * 绑定/解绑血压仪或体重秤
     */
    @ApiOperation("绑定/解绑血压仪或体重秤")
    @Log(title = "绑定/解绑血压仪或体重秤", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeyuDevice deyuDevice)
    {
        if(Objects.isNull(deyuDevice) || Objects.isNull(deyuDevice.getId())){
            return error("设备id不能为空");
        }
        deyuDevice.setUserId(getUserId());
        return toAjax(deyuDeviceService.updateDeyuDeviceFixed(deyuDevice));
    }


    /**
     * 授权/取消授权医院
     */
    @ApiOperation("授权/取消授权医院，传参为授权，不传则取消授权")
    @ApiImplicitParam(name = "hospitalId", value = "授权医院ID", required = false, dataType = "Long", paramType = "query", dataTypeClass = Long.class)
    @PostMapping("/authHospital")
    public AjaxResult authHospital(@RequestParam(value = "hospitalId", required = false) Long hospitalId) {
        SysUser user = new SysUser();
        user.setUserId(getUserId());
        user.setDeptId(hospitalId);
        return toAjax(deyuSysUserService.updateDept(user));
    }


    @ApiOperation("一体机日志文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "日志文件", required = true, dataType = "file", paramType = "form", dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "deviceMac", value = "设备mac地址", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
    })
    @PostMapping("/logUpload/{deviceMac}")
    public AjaxResult uploadFile(MultipartFile file, @PathVariable("deviceMac") String deviceMac) throws Exception {
        try {
            deyuLogFileService.processLogFile(file, getUserId(),deviceMac);
            return AjaxResult.success("上传成功");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询最新上架的3条资讯信息列表
     */
    @ApiOperation("查询最新上架的3条资讯信息列表")
    @GetMapping("/deyuArticle/list")
    public AjaxResult list()
    {
        DeyuArticle deyuArticle = new DeyuArticle();
        deyuArticle.setState(0L);
        PageHelper.startPage(1, 3, "update_time desc").setReasonable(true);
        List<DeyuArticle> list = deyuArticleService.selectDeyuArticleList(deyuArticle);
        return AjaxResult.success(list);
    }

}
